#coding=utf-8
from sqlalchemy.orm import *

from stockdb.domains import *
import stockdb.tables as tables

def stockdb_mapping():
    mapper(FInstrucment, tables.finstrucments, 
           polymorphic_on = tables.finstrucments.c.type, 
           polymorphic_identity = 'finstrucment')
           
    mapper(SIndex, tables.sindex, inherits = FInstrucment, polymorphic_identity = 'sindex')       
    mapper(Stock, tables.stock, inherits = FInstrucment, polymorphic_identity = 'stock')

    mapper(TradableShare, tables.tradableshare, 
           order_by = tables.tradableshare.c.date.desc(),
           properties = {'stock':
                          relation(Stock, 
                                   backref = backref('tss', cascade="all, delete, delete-orphan"))})
                                   
    mapper(FuQuanRatio, tables.fuquanratio, 
           order_by = tables.fuquanratio.c.date.desc(),
           properties = {'stock':
                          relation(Stock, 
                                   backref = backref('fqrs', cascade="all, delete, delete-orphan"))})
                                                                  
    mapper(TradeDay, tables.tradedays, 
           order_by = tables.tradedays.c.date.desc(),
           properties = {'pre':relation(TradeDay, backref=backref('next', remote_side=tables.tradedays.c.id), uselist=False),
                         'fins':relation(FInstrucment, 
                                        backref = backref('tds', cascade="all, delete, delete-orphan"))})
          
    mapper(Price, tables.price,
           properties = {'td':relation(TradeDay, 
                                       backref = backref('price', cascade="all, delete, delete-orphan" , uselist=False) ) })
                                       
    mapper(Deal2, tables.deals,
           properties = {'td':relation(TradeDay, backref='deals')}
           )
                                       
    mapper(TdCache, tables.tdcache,
           properties = {'td':relation(TradeDay, 
                                       backref = backref('tdcaches')) })
                                       #, cascade="all, delete, delete-orphan")) })
                                       
    mapper(RTPrice, tables.rpcache, 
           properties = {'stock':
                          relation(Stock, backref = backref('rps'))}                          
    )
    
    mapper(TDStats, tables.tdstats,
           properties = {'td':relation(TradeDay, backref = backref('stats', uselist=False))})
           
    mapper(DealStats, tables.dealstats,
           properties = {'td':relation(TradeDay)})
